package com.fisicaapp;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.MaskFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Acttrayectoria extends Activity implements OnTouchListener{
	
    private int ancho, alto;        
    private Panel fondo;
    private Paint       mPaint;
    private MaskFilter  mEmboss;
    private MaskFilter  mBlur;

    private TextView txt_info1 ;
    private TextView txt_info2 ;
    //private TextView txt_vector3 ; 
    private Button botonGrafico1,botonGrafico2, botonLimpiar;    
	private DecimalFormat df ; // variable para dejar formato de numeros en dos decimales
	private VelocityTracker velocityTracker;
    
    private Trayectoria trayectoria;    
    
    private static final int TOLERANCE_PX = 0; //cada cuantos px sumo
    private static final float PX_TO_CM = 0.01f;
    
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.cinematicatrayectoria);

	
	    txt_info1 = (TextView) findViewById(R.id.text_vector221);
	    txt_info2 = (TextView) findViewById(R.id.text_vector222);
	    //txt_vector3 = (TextView) findViewById(R.id.text_vector23);       
	    txt_info1.setText("");
		txt_info2.setText("");    
	    RelativeLayout layout = (RelativeLayout) findViewById(R.id.layoutXX2); 
	    ancho=(int) (getWindowManager().getDefaultDisplay().getWidth()); 
	    alto=(int) (getWindowManager().getDefaultDisplay().getHeight());
	    
	    trayectoria = new Trayectoria();
	   
	    velocityTracker = VelocityTracker.obtain();
	    botonGrafico1 = (Button) findViewById(R.id.button221);
	    botonGrafico2 = (Button) findViewById(R.id.button222);
	    botonLimpiar = (Button) findViewById(R.id.button223);    
	   
	    botonGrafico1.setEnabled(false);
	    botonGrafico2.setEnabled(false);
	    botonLimpiar.setEnabled(false);    
	    
	    df = new DecimalFormat("0.00"); // defino que formato decimal sera de dos decimales (se trunca)
	    
	    
	    mPaint = new Paint();
	    mPaint.setAntiAlias(true);
	    mPaint.setDither(true);
	    mPaint.setColor(Color.RED);
	    mPaint.setStyle(Paint.Style.STROKE);
	    mPaint.setStrokeJoin(Paint.Join.ROUND);
	    mPaint.setStrokeCap(Paint.Cap.ROUND);
	    mPaint.setStrokeWidth(2);        
	    mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
	    mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
	    
	    fondo = new Panel(this);
	    fondo.setOnTouchListener(this);
	    layout.addView(fondo);
	}

 

//Accion al volver!
public void volver(View view) {
   finish();
}


public void graficarPosicion(View view){
	Intent i;
	
	i = new Intent(this , SampleChart.class);
	
	double px[]=trayectoria.arrayListIntoArrayDouble(trayectoria.getPosX());	
	double py[]=trayectoria.arrayListIntoArrayDouble(trayectoria.getPosY());
	double t[] = trayectoria.arrayListIntoArrayDouble(trayectoria.getTiempos());	
	Bundle bundles = new Bundle();
	bundles.putString("yourkey_data", "1");
	bundles.putDoubleArray("yourkeyt", t);
	bundles.putDoubleArray("yourkey1", px);
	bundles.putDoubleArray("yourkey2", py);
	i.putExtras(bundles);	
	startActivity(i);
	
}

public void graficarVelocidad(View view){
	Intent i;	
	i = new Intent(this , SampleChart.class);	
	double vx[]=trayectoria.arrayListIntoArrayDouble(trayectoria.getVelX());	
	double vy[]=trayectoria.arrayListIntoArrayDouble(trayectoria.getVelY());
	double t[] = trayectoria.arrayListIntoArrayDouble(trayectoria.getTiempos());	
	Bundle bundles = new Bundle();
	bundles.putString("yourkey_data", "2");
	bundles.putDoubleArray("yourkeyt", t);
	bundles.putDoubleArray("yourkey1", vx);
	bundles.putDoubleArray("yourkey2", vy);
	i.putExtras(bundles);	
	startActivity(i);
	
}

public void limpiar(View v){
	limpiarVariables();
	 
}
public void limpiarVariables(){
	
	fondo.limpiarTrazos();
	txt_info1.setText("");
	txt_info2.setText("");
	trayectoria.cleanAll();		
	botonGrafico1.setEnabled(false);
	botonGrafico2.setEnabled(false);
	botonLimpiar.setEnabled(false);
	
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.    
	getMenuInflater().inflate(R.menu.menu_cinem, menu);
    return true;
}

protected void onResume() {
    super.onResume();   
}


protected void onStop() {	
    super.onStop();
}


public boolean onOptionsItemSelected(MenuItem item) { //acciones para los elementos del menu
	Intent i;
    switch (item.getItemId()) {
    case R.id.Datos21:
    	
        break;   
   
    case R.id.Volver22:
    	finish();
        
    }
    return true;
}



//EVENTOS
public boolean onTouch(View v, MotionEvent event) { 		
	    float x = event.getX();
        float y = event.getY();
        double dx, dy;
        float tFinal,time;
        long current_time;
        velocityTracker.addMovement(event);
		velocityTracker.computeCurrentVelocity(1000);
		float x_velocity = velocityTracker.getXVelocity();
		float y_velocity = -velocityTracker.getYVelocity();
		trayectoria.addPosXY(x - (ancho/2), -(y- (alto/2)));
		trayectoria.addVelXY(x_velocity, y_velocity);
		
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            	
            	if (trayectoria.getTiempoPivote() == 0) trayectoria.setTiempoPivote(event.getEventTime());
            	
            	trayectoria.setPosInicialXY(x,y,0);            	
            	trayectoria.setPosAnteriorXY(x,y,0);            	        	
            	trayectoria.addTiempo(0);
                fondo.touch_start(x, y);
                //fondo.invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
            	current_time = event.getEventTime();
            	dx = Math.abs((x - trayectoria.getPosAnteriorX()));
            	dy = Math.abs((y - trayectoria.getPosAnteriorY()));  
            	trayectoria.updateDistRecorridaTotal(dx, dy);            	
            	time = (current_time - trayectoria.getTiempoPivote())/1000;
            	trayectoria.addTiempo(time);        		                 
        		fondo.touch_move(x, y);
        		trayectoria.setPosAnteriorXY(x,y,time);                
                //fondo.invalidate();
                break;
            case MotionEvent.ACTION_UP:
            	current_time = event.getEventTime();
            	tFinal = (current_time - trayectoria.getTiempoPivote())/1000;
            	dx = Math.abs((x - trayectoria.getPosAnteriorX()));
            	dy = Math.abs((y - trayectoria.getPosAnteriorY()));  
            	trayectoria.updateDistRecorridaTotal(dx, dy);            	
            	trayectoria.setPosFinalXY(x, y, tFinal);
            	trayectoria.addTiempo(tFinal);
            	
            	//Imprimir cosas
            	txt_info1.setText(
            			"t. total: "+df.format(tFinal) +" [s]"+Html.fromHtml("<br/>")+            					
            	        "dist. Total: "+df.format((trayectoria.getDistRecorridaTotal())) +"[m]"
            			);
            	txt_info2.setText(
            	"desp. X: " + 
            	df.format(trayectoria.getDesplazamientoX()) +"[m]"+Html.fromHtml("<br/>")+
            	"desp. Y: " + 
            	df.format(trayectoria.getDesplazamientoY()) +"[m]"+Html.fromHtml("<br/>")            	
            			);            	
            	
            	botonGrafico1.setEnabled(true);
            	botonGrafico2.setEnabled(true);
            	botonLimpiar.setEnabled(true);            	     
            	
                fondo.touch_up();
                //fondo.invalidate();
                break;
        }
        return true;
    }



//Panel para pintar!
class Panel extends View{
	
	
	private static final float MINP = 0.25f;
    private static final float MAXP = 0.75f;
    
    private Bitmap  mBitmap;
    private Canvas  mCanvas;
    private Path    mPath;
    private Paint   mBitmapPaint;
   
    public Panel(Context context) {
        super(context);       
       
       // cada linea es un pincel        
        txt_info1.setTextColor(Color.RED);
        
        mBitmap = Bitmap.createBitmap(ancho, alto, Bitmap.Config.ALPHA_8);
        //mBitmap.recycle();
     
        mCanvas = new Canvas(mBitmap);
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        mBitmapPaint.setColor(Color.RED);
       
    }
    @Override
    protected void onDraw(Canvas canvas) {
    	
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);        
        canvas.drawPath(mPath, mPaint);
    }
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }
    
    
    private float mX, mY;
    private static final float TOUCH_TOLERANCE = 10;
    
    private void touch_start(float x, float y) {
        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }
    private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
            mX = x;
            mY = y;
        }
    }
    private void touch_up() {
        mPath.lineTo(mX, mY);
        // commit the path to our offscreen
        mCanvas.drawPath(mPath, mPaint);
        // kill this so we don't double draw
        mPath.reset();
        fondo.setEnabled(false); 
        
     
    	
    }
    
    private void limpiarTrazos(){

    	mPath.reset();

        fondo.setEnabled(true); 
    	mBitmap.eraseColor(android.graphics.Color.TRANSPARENT);
    	
    }
    
     	
        
    
} // termina la clase Panel



}
  